package com.niiwoo.civet.trade.service.local.orgloan;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.trade.constant.DatePatternConstant;
import com.niiwoo.civet.trade.constant.enums.CreditRepaymentTypeEnum;
import com.niiwoo.civet.trade.dao.entity.orgloan.OrgLoanProject;
import com.niiwoo.civet.trade.dao.entity.orgloan.OrgLoanProjectInvestor;
import com.niiwoo.civet.trade.dao.mapper.ProjectMapper;
import com.niiwoo.civet.trade.dao.mapper.credit.*;
import com.niiwoo.civet.trade.dao.mapper.orgloan.OrgLoanProjectInvestorMapperExt;
import com.niiwoo.civet.trade.dao.mapper.orgloan.OrgLoanProjectMapperExt;
import com.niiwoo.civet.trade.dto.request.orgloan.LoanOrgInfoResponseDTO;
import com.niiwoo.civet.trade.dto.request.orgloan.OrgLoanInvestProjectRequestDTO;
import com.niiwoo.civet.trade.dto.request.orgloan.OrgProjectIdReqDTO;
import com.niiwoo.civet.trade.dto.response.credit.*;
import com.niiwoo.civet.trade.dto.response.orgloan.OrgInfoResponseDTO;
import com.niiwoo.civet.trade.dto.response.orgloan.QueryOrgLoanContractReponseDTO;
import com.niiwoo.civet.trade.dto.response.orgloan.QueryOrgLoanInvestInfoReponseDTO;
import com.niiwoo.civet.trade.enums.ProjectStatusEnum;
import com.niiwoo.civet.trade.enums.credit.CreditLoanGuaranteeProjectStatusEnum;
import com.niiwoo.civet.trade.service.org.OrgProjectDubboService;
import com.niiwoo.civet.trade.utils.SysStringUtils;
import com.niiwoo.tripod.base.utils.DateUtils;
import com.niiwoo.tripod.provider.dto.response.PageResponseDTO;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 信用借.
 */
@Service
public class OrgLoanService {

    /**
     * 金额的精度
     */
    private static final int INVESTMENT_PRECISION_TWO = 2;
    @Autowired
    private OrgLoanProjectMapperExt orgLoanProjectMapperExt;

    @Autowired
    private OrgLoanProjectInvestorMapperExt orgLoanProjectInvestorMapperExt;

    @Autowired
    private CreditProjectGuaranteeMapperExt creditProjectGuaranteeMapperExt;

    @Autowired
    private ProjectMapper projectMapper;

    @Reference(version = "1.0.0")
    private OrgProjectDubboService orgProjectDubboService;
    /**
     * 机构极速借查询投资记录
     *
     * @param requestDTO
     * @return
     */
    public PageResponseDTO<QueryOrgLoanInvestInfoReponseDTO> queryOrgLoanProjectInfoList(OrgLoanInvestProjectRequestDTO requestDTO) {

        PageResponseDTO<QueryOrgLoanInvestInfoReponseDTO> pageResult = new PageResponseDTO<QueryOrgLoanInvestInfoReponseDTO>();
        List<QueryOrgLoanInvestInfoReponseDTO> result=new ArrayList<>();
            // 增加分页参数
        int offset=(requestDTO.getPageNumber() - 1) * requestDTO.getPageSize();
        int rows=requestDTO.getPageSize();
        List<OrgLoanProjectInvestor> infoList = orgLoanProjectInvestorMapperExt.selectByUserId(requestDTO.getUserId(),offset,rows);
        int count = orgLoanProjectInvestorMapperExt.selectMyInvestCount(requestDTO.getUserId());
        if(count>0){
            for (OrgLoanProjectInvestor orgLoanProjectInvestor : infoList) {
                if (orgLoanProjectInvestor != null) {
                    QueryOrgLoanInvestInfoReponseDTO InfoReponseDTO = new QueryOrgLoanInvestInfoReponseDTO();
                    OrgLoanProject orgLoanProject = orgLoanProjectMapperExt.selectByPrimaryKey(orgLoanProjectInvestor.getProjectId());
                    if(orgLoanProject!=null){
                        InfoReponseDTO.setId(orgLoanProjectInvestor.getId());
                        InfoReponseDTO.setProjectId(orgLoanProject.getProjectId());
                        InfoReponseDTO.setBorrowerUserId(orgLoanProject.getBorrowUserId());
                        InfoReponseDTO.setBorrowerGender(orgLoanProject.getBorrowSex());
                        InfoReponseDTO.setBorrowerHeadImage(orgLoanProject.getBorrowHeadImg());
                        InfoReponseDTO.setBorrowerNickName(orgLoanProject.getBorrowNickName());
                        InfoReponseDTO.setBorrowRate(orgLoanProject.getBorrowRate());
                        InfoReponseDTO.setBorrowAmount(orgLoanProject.getContractAmount());
                        InfoReponseDTO.setDeadLine(orgLoanProject.getDeadline());
                        InfoReponseDTO.setDeadlineUnit(orgLoanProject.getDeadlineUnit());
                        InfoReponseDTO.setTitle(orgLoanProject.getTitle());
                        if(orgLoanProject.getFullSuccessTime()!=null) {
                            InfoReponseDTO.setFullSuccessDate(DateFormatUtils.format(orgLoanProject.getFullSuccessTime(),
                                    DatePatternConstant.YYYY_MM_DD_HH_MM_SS));
                        }
                        //发布时间
                        InfoReponseDTO.setCreateTime(DateFormatUtils.format(orgLoanProject.getCreateTime(),
                                DatePatternConstant.YYYY_MM_DD_HH_MM_SS));
                        BigDecimal investNumber = new BigDecimal(orgLoanProjectInvestor.getInveNumber().intValue());
                        InfoReponseDTO.setInvestedAmount(investNumber.multiply(orgLoanProjectInvestor.getAmountPer()));
                        InfoReponseDTO.setLoanCity(orgLoanProject.getLoanCity());
                        InfoReponseDTO.setLoanArea(orgLoanProject.getLoanArea());
                        InfoReponseDTO.setRevenue(orgLoanProjectInvestor.getRevenue());
                        //流标
                        if(orgLoanProject.getProjectstatus().equals(CreditLoanGuaranteeProjectStatusEnum.GUARANTEE_NOT_PASS.getCode())
                                || orgLoanProject.getProjectstatus().equals(CreditLoanGuaranteeProjectStatusEnum.LOAN_FAILURE.getCode())
                                || orgLoanProject.getProjectstatus().equals(CreditLoanGuaranteeProjectStatusEnum.LOAN_FAILURE_MANUAL.getCode())
                                || orgLoanProject.getProjectstatus().equals(CreditLoanGuaranteeProjectStatusEnum.INVESTIGATE_NOT_PASS.getCode())){
                            InfoReponseDTO.setStatus(ProjectStatusEnum.MISCARRY.getStatus());

                        } else {
                            //已结清
                            InfoReponseDTO.setStatus(ProjectStatusEnum.FINISH.getStatus());
                            InfoReponseDTO.setText("本次还款已结清，欢迎关注平台其他投资标的");
                        }
                        InfoReponseDTO.setContractUrl(orgLoanProject.getContractUrl());
                    }
                    result.add(InfoReponseDTO);
                }
            }
            try {
                sort(result);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        pageResult.measureTotalPage(count,requestDTO.getPageSize());
        pageResult.setItems(result);
        pageResult.setTotalCount(count);
        return pageResult;
    }

    /**
     * 排序按照已结清>流标、再按满标或发布时间排序。
     */
    private void sort( List<QueryOrgLoanInvestInfoReponseDTO> result) {
        Collections.sort(result, new Comparator<QueryOrgLoanInvestInfoReponseDTO>() {
            @Override
            public int compare(QueryOrgLoanInvestInfoReponseDTO o1, QueryOrgLoanInvestInfoReponseDTO o2) {
                int flag = o1.getStatus().byteValue() - o2.getStatus().byteValue();
                if (flag > 0) {
                    return 1;
                } else if (flag == 0 && ProjectStatusEnum.FINISH.getStatus().equals(o1.getStatus())) {
                    int fullDate = DateUtils.compareDate(DateUtils.parseDateFromString(o1.getFullSuccessDate(), DatePatternConstant.YYYY_MM_DD_HH_MM_SS),
                            DateUtils.parseDateFromString(o2.getFullSuccessDate(), DatePatternConstant.YYYY_MM_DD_HH_MM_SS));
                    //已结清
                    if (fullDate > 0) {
                        return 1;
                    } else if(fullDate < 0) {
                        return fullDate;
                    }else{
                        return 0;
                    }
                } else if (flag == 0 && ProjectStatusEnum.MISCARRY.getStatus().equals(o1.getStatus())) {
                    int createDate = DateUtils.compareDate(DateUtils.parseDateFromString(o1.getCreateTime(), DatePatternConstant.YYYY_MM_DD_HH_MM_SS),
                            DateUtils.parseDateFromString(o2.getCreateTime(), DatePatternConstant.YYYY_MM_DD_HH_MM_SS));
                    //流标
                    if (createDate > 0) {
                        return 1;
                    } else if(createDate < 0){
                        return createDate;
                    }else{
                        return 0;
                    }
                } else if (flag < 0) {
                    return flag;
                }else{
                    return 0;
                }
            }
        });
    }

    /**
     * 机构极速借查询合同参数
     *
     * @param userId
     * @return
     */
    public QueryOrgLoanContractReponseDTO queryOrgLoanContractParas(Long projectId, String userId) {
        OrgLoanProjectInvestor orgLoanProjectInvestor=new OrgLoanProjectInvestor();
        OrgLoanProject orgLoanProject=new OrgLoanProject();
        List<OrgLoanProjectInvestor> investList = orgLoanProjectInvestorMapperExt.selectByProjectIdAndUserId(projectId,userId);
        if (null != investList && 0 < investList.size()) {
            orgLoanProjectInvestor = investList.get(0);
           orgLoanProject=orgLoanProjectMapperExt.selectByPrimaryKey(orgLoanProjectInvestor.getProjectId());
        }
        QueryOrgLoanContractReponseDTO result = getContractContentShow(orgLoanProject,userId);
        return result;
    }

	public QueryOrgLoanContractReponseDTO getContractContentShow(OrgLoanProject orgLoanProject,String userId) {
        QueryOrgLoanContractReponseDTO result=new QueryOrgLoanContractReponseDTO();
       List<InvestUserDTO> investInfoList= new ArrayList<InvestUserDTO>();
        List<OrgLoanProjectInvestor> investList = orgLoanProjectInvestorMapperExt.selectByProjectId(orgLoanProject.getProjectId());
         if(investList!=null){
           for (OrgLoanProjectInvestor orgLoanProjectInvestor : investList) {
               if (orgLoanProjectInvestor != null) {
                   InvestUserDTO investUserDTO=new InvestUserDTO();
                   investUserDTO.setInvestId(orgLoanProjectInvestor.getInvestorUserId());
                   if(!userId.equals(orgLoanProjectInvestor.getInvestorUserId())){
                       investUserDTO.setInvestName(SysStringUtils.encryptionRealName(orgLoanProjectInvestor.getInvestorRealName(),1));
                   }else{
                       investUserDTO.setInvestName(orgLoanProjectInvestor.getInvestorRealName());
                   }
                   BigDecimal investNumber = new BigDecimal(orgLoanProjectInvestor.getInveNumber().intValue());
                   BigDecimal investAmount = investNumber.multiply(orgLoanProjectInvestor.getAmountPer());
                   if(investAmount!=null){
                       investUserDTO.setInvestAmount(investAmount);
                   }
                   investInfoList.add(investUserDTO);
               }
           }
       }
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");

       if(orgLoanProject!=null){
           result.setBorrowId(orgLoanProject.getBorrowUserId());
           result.setBorrowAmount(orgLoanProject.getContractAmount());
           if(!userId.equals(orgLoanProject.getBorrowUserId())){
               String encryptBorrowRealName=SysStringUtils.encryptionRealName(orgLoanProject.getBorrowRealName(),1);
               result.setBorrowName(encryptBorrowRealName);
               result.setAddress(SysStringUtils.encryptionRealName(orgLoanProject.getLoanCity()+orgLoanProject.getLoanArea(),1));
           }else{
               result.setBorrowName(orgLoanProject.getBorrowRealName());
               result.setAddress(orgLoanProject.getLoanCity()+orgLoanProject.getLoanArea());
           }
           //期限
           result.setDeadline(orgLoanProject.getDeadline());
           //期限单位
           result.setDeadlineUnit(orgLoanProject.getDeadlineUnit());
           if(orgLoanProject.getServiceFee()!=null){
               //平台服务费
               BigDecimal platformServiceAmount=orgLoanProject.getServiceFee().setScale(INVESTMENT_PRECISION_TWO,BigDecimal.ROUND_HALF_UP);
               result.setBorrowPlatformServiceFee(platformServiceAmount);
           }
           if(orgLoanProject.getManageFee()!=null){
               //平台管理费
               BigDecimal manageFee=orgLoanProject.getManageFee().setScale(INVESTMENT_PRECISION_TWO,BigDecimal.ROUND_HALF_UP);
               result.setBorrowPlatformServiceFee(manageFee);
           }
           //罚息日率
           result.setPenaltyRate(orgLoanProject.getPenaltyRate().divide(new BigDecimal("100")));
           //支付担保人担保费
           if(orgLoanProject.getContractAmount()!=null){
               BigDecimal guarantorServiceAmount = orgLoanProject.getContractAmount().multiply(orgLoanProject.getGuaranteeRate())
                       .divide(new BigDecimal(100));
               result.setGuaranteeFee(guarantorServiceAmount.setScale(INVESTMENT_PRECISION_TWO, BigDecimal.ROUND_HALF_UP));
           }
           if (null != orgLoanProject.getFullSuccessTime()) {
               //合同生效时间
               result.setEffectiveDate(sdf.format(orgLoanProject.getFullSuccessTime()));
               //还款时间
               result.setRefundDate(sdf.format(getContractRepaymentDate(orgLoanProject)));
           }
           //车马费
           result.setHorseFee(orgLoanProject.getHorseFee().setScale(INVESTMENT_PRECISION_TWO,BigDecimal.ROUND_HALF_UP));
           result.setRepaymentType(orgLoanProject.getRepaymentType());
           String repaymentTypeName = "";
           if(orgLoanProject.getRepaymentType()!=null){
                switch (orgLoanProject.getRepaymentType()) {
                    case 1:
                        repaymentTypeName = CreditRepaymentTypeEnum.REPAY_PRINCIPAL_INTEREST_AT_TERM.getDesc();
                        break;
                    case 2:
                        repaymentTypeName = CreditRepaymentTypeEnum.REPAY_PRINCIPAL_AT_TERM.getDesc();
                        break;
                    case 5:
                        repaymentTypeName = CreditRepaymentTypeEnum.AVERAGE_CAPITAL_PLUS_INTEREST.getDesc();
                        break;
                    default:
                        repaymentTypeName = "未知";
                        break;
               }
           }
           result.setRepaymentTypeName(repaymentTypeName);
           //年利率
           result.setYearRate(orgLoanProject.getBorrowRate().divide(new BigDecimal("100")));
           result.setLoanCity(orgLoanProject.getLoanCity());
           result.setLoanArea(orgLoanProject.getLoanArea());

       }
       result.setInvestUserList(investInfoList);
       return result;
   }

    /**
     * 获取还款时间,满标时间+借款期限（天，月）
     */
    public Date getContractRepaymentDate(OrgLoanProject orgLoanProject){

        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        String time=sim.format(orgLoanProject.getFullSuccessTime());
        String[] arrDate = time.split("-");
        int iYear = Integer.valueOf(arrDate[0]);
        int iMonth = Integer.valueOf(arrDate[1]);
        int iDay = Integer.valueOf(arrDate[2]);
        calendar.set(iYear, iMonth, iDay);
        //借款期限单位(0:月，1:天)
        if(orgLoanProject.getDeadlineUnit()==0){
            calendar.add(Calendar.MONTH, orgLoanProject.getDeadline()-1);//因为Month值从0开始，所以取得的值应该减去1
        }else if(orgLoanProject.getDeadlineUnit()==1){
            calendar.add(Calendar.DATE, orgLoanProject.getDeadline());
        }
        return calendar.getTime();

    }
    /**
     * 判断用户是否存在信用借(1，存在，0不存在)
     */
    public int queryOrgLoanProject(String userId) {
        int count = orgLoanProjectInvestorMapperExt.selectMyInvestCount(userId);
        if(count==0){
            return 0;
        }else{
            return 1;
        }
    }

}


